package zen_group.mdl;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import zen_group.exc.InvalidDataFormat;
import zen_group.exc.InvalidSource;
import zen_group.ifc.PartReader;


public class XlsPartReader
        implements PartReader
{
    private Vector<Part>    mItems;


    public
    XlsPartReader(File source) throws InvalidSource
    {
        try
        {
            mItems  = readFile(source);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new InvalidSource(source.getAbsolutePath());
        }
    }


    public Vector<Part>
    readFile(File s) throws Exception
    {
        Vector<Part>    items   = new Vector<Part>(10, 10);

        FileInputStream stream  = new FileInputStream(s.getAbsolutePath());
        POIFSFileSystem fs      = new POIFSFileSystem(stream);
        HSSFWorkbook    book    = new HSSFWorkbook(fs);
        HSSFSheet       sheet   = book.getSheetAt(0);

        Iterator        rows    = sheet.rowIterator();
        try
        {
            mItems.add(readPart((HSSFRow)rows.next()));
        }
        catch (Exception e)
        {
            // ignoring exceptions in title row
        }

        for (; rows.hasNext(); items.add(readPart((HSSFRow)rows.next())))
            ;   // NO BODY

        return items;
    }

    public Part
    readPart(HSSFRow row) throws Exception
    {
        Iterator cells  = row.cellIterator();
        return new Part(
                readString((HSSFCell)cells.next()),
                (int)readNumber((HSSFCell)cells.next()),
                (float)readNumber((HSSFCell)cells.next()),
                (float)readNumber((HSSFCell)cells.next())
            );
    }

    public String
    readString(HSSFCell cell)
    {
        //if (cell.getCellType() != HSSFCell.CELL_TYPE_STRING)
        //    throw new Exception();

        //String title    = cell.getRichStringCellValue().getString();
        return cell.toString();
    }


    public double
    readNumber(HSSFCell cell) throws InvalidDataFormat
    {
        if (cell.getCellType() != HSSFCell.CELL_TYPE_NUMERIC)
            throw new InvalidDataFormat();

        return cell.getNumericCellValue();
    }


    public Vector<Part>
    getItems()
    {
        return mItems;
    }
}
